<!--<style rel="stylesheet/scss" lang="scss" scoped>-->
  <!--.svg-container {-->
    <!--padding: 6px 5px 6px 15px;-->
    <!--color: $dark_gray;-->
    <!--vertical-align: middle;-->
    <!--width: 30px;-->
    <!--display: inline-block;-->
    <!--&_login {-->
     <!--font-size: 20px;-->
   <!--}-->
  <!--}-->
  <!--.show-pwd {-->
    <!--position: absolute;-->
    <!--right: 10px;-->
    <!--top: 7px;-->
    <!--font-size: 16px;-->
    <!--color: $dark_gray;-->
    <!--cursor: pointer;-->
    <!--user-select: none;-->
  <!--}-->
<!--</style>-->
<template>
  <div>
    <el-button type="primary" @click="addUser()">{{$t('table.add')}}</el-button>
    <el-dialog :visible.sync="dialogTableVisible" :title="$t('table.add')" width="970px">
      <el-form ref="row_data" :model="row_data" :rules="rules" label-position="left" label-width="auto" style="width: 400px; margin-left:50px;">

        <el-form-item :label="$t('authority.username')" prop="phone">
          <el-input v-model="row_data.phone" style="width: 200px" />
        </el-form-item>

        <!--<el-form-item label="用户密码" prop="password">-->
        <!--<el-input v-model="row_data.password" placeholder="用户密码" style="width: 200px"/>-->
        <!--</el-form-item>-->
        <el-form-item :label="$t('login.password')" prop="password">
          <el-input :type="passwordType" v-model="row_data.password" name="password" auto-complete="on" style="width: 200px"
            @keyup.enter.native="handleLogin">
            <span slot="prefix" class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <span slot="suffix" class="show-pwd" @click="showPwd">
              <svg-icon icon-class="eye" />
            </span>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('authority.nickname')" prop="nickname">
          <el-input v-model="row_data.nickname" style="width: 200px" />
        </el-form-item>
        <el-form-item :label="$t('authority.status')" prop="">
          <el-select v-model="row_data.status" class="filter-item" clearable @keyup.enter.native="handleFilter">
            <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('authority.authority')" prop="">
          <el-select v-model="row_data.role_id" class="filter-item" clearable>
            <el-option v-for="(item, index) in shop_role" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.avatar')" prop="product_main_photo">
          <!--<el-alert title="建议图片尺寸为 宽 x 高 px" style="margin-bottom: 10px; line-height: 20px" type="success"/>-->
          <div class="upload_product_main_photo">
            <!-- <el-alert
              title="建议图片像素（750px * 750px）"
              type="warning"
              show-icon
              style="margin-bottom: 10px; line-height: 20px; width: 280px"
              close-text="知道了"/> -->
            <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="upload_product_main_photo" class="avatar-uploader"
              action="">
              <img v-if="face_pic" :src="face_pic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">{{$t('table.complete')}}</el-button>
          <el-button @click="close()">{{$t('table.cancel')}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from "@/directive/el-dragDialog"; // base on element-ui
import { add } from "@/api/user/admin_user";
import { client } from "@/utils/alioss";
// import { getUserInfoList } from '@/api/user/user'
import { getShopRoleList } from "@/api/shop_admin_auth/shopRole";
import store from "@/store";
export default {
  name: "DragDialogDemo",
  directives: { elDragDialog },
  data() {
    const validateUsername = (rule, value, callback) => {
      callback();
    };
    const validatePassword = (rule, value, callback) => {
      if (!value || value.length < 8) {
        callback(new Error(this.$t("validation.password1")));
      } else {
        callback();
      }
    };
    return {
      rules: {
        nickname: [
          {
            required: true,
            message: this.$t("validation.nickname"),
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: this.$t("validation.phone"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("validation.password"),
            trigger: "blur",
          },
          { validator: validatePassword, trigger: "blur" },
        ],
        status: [
          {
            required: true,
            message: this.$t("validation.status"),
            trigger: "blur",
          },
        ],
        role_id: [
          {
            required: true,
            message: this.$t("validation.role_id"),
            trigger: "blur",
          },
        ],
      },
      status: [
        {
          value: 1,
          label: this.$t("authority.on"),
        },
        {
          value: 0,
          label: this.$t("authority.off"),
        },
      ],
      dialogTableVisible: false,
      list: [],
      role_id: null,
      row_data: {
        status: 1,
      },
      loginForm: {
        username: "",
        password: "",
      },
      shop_role: [],
      // loginRules: {
      //   username: [{ required: true, trigger: 'blur', validator: validateUsername }],
      //   password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      // },
      passwordType: "password",
      loading: false,
      showDialog: false,
      face_pic: "",
      base64: "",
      base64type: "",
    };
  },
  created() {},
  methods: {
    addUser() {
      this.dialogTableVisible = true;
      this.getUserInfo();
      this.get_shop_role_list();
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
    },
    valueItem(index) {
      for (let i = 0; i < this.list.length; i += 1) {
        if (this.list[i].id === index) {
          this.row_data.phone = this.list[i].phone;
        }
      }
    },
    getUserInfo() {
      // getUserInfoList(store.getters.token).then(response => {
      //   this.list = response.data.list.data
      // })
    },
    get_shop_role_list() {
      getShopRoleList(store.getters.token).then((response) => {
        console.log(response.data.data);
        this.shop_role = response.data.data;
      });
      // getShopRoleList(store.getters.token).then(res => {
      //   this.shop_role = res.data.list.data
      // })
    },
    // 上传图片
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error(this.$t("validation.img_tip1"));
        return false;
      }
      if (!isLt2M) {
        this.$message.error(this.$t("validation.img_tip2"));
        return false;
      }
      return isJPG | isPNG && isLt2M;
    },
    upload_product_main_photo(file) {
      const that = this;
      const fileName = "meirijiemi" + file.file.uid;
      client()
        .put(fileName, file.file)
        .then((res) => {
          // this.$set(that.face_pic, res.url);
          this.face_pic = res.url;
          // that.$message.success('图片上传成功！')
        })
        .catch((err) => {
          // that.$message.error('图片上传失败，原因：' + err)
        });

        // 获取base64
      var reader = new FileReader();
      // 创建一个img对象
      var img = new Image();
      reader.readAsDataURL(file.file);
      reader.onload = (e) => {
        // this.base64 = reader.result.split(",")[1];
        this.base64type = reader.result.split(",")[0];

        img.src = e.target.result;
        // base64地址图片加载完毕后执行
        img.onload = function () {
          // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
          var canvas = document.createElement("canvas");
          var context = canvas.getContext("2d");
          // 图片原始尺寸
          var originWidth = this.width;
          that.widthsize = originWidth;
          var originHeight = this.height;
          that.heightsize = originHeight;
           

          // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
          var maxWidth = 300,
            maxHeight = 300;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过最大尺寸的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更改宽度，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }
          // 对图片进行缩放
          canvas.width = targetWidth;
          // console.log( canvas.width,' canvas.width')
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
          /* 第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
          // 压缩后的base64文件
           that.base64 = canvas.toDataURL("image/jpeg", 0.92);
          // that.base64 = newUrl.split(",")[1];
          // that.face_pic = that.base64;
          // that.base64type = newUrl.split(",")[0];
          // console.log(that.base64type,'base64type')
          // console.log(newUrl, '0000000000000000000000000000000')
        };
      };
        
    },
    submitForm() {
      this.$refs.row_data.validate((valid) => {
        if (valid) {
          console.log(this.base64,'ttttt11')
          console.log(this.face_pic,'ttttt')
          var data = {
            head_img: this.base64,
            password : this.row_data.password,
            phone : this.row_data.phone,
            status: this.row_data.status,
            username: this.row_data.username,
            role_id: this.row_data.role_id,
            nickname:this.row_data.nickname
          }
          add(store.getters.token, data).then((res) => {
            if (res.data.status === true) {
              this.$message({
                message: this.$t("table.add_complete"),
                type: "success",
              });
              this.row_data = {};
              this.$emit("getLists");
            this.close();
            }else if(res.data.msg == '添加失败'){
              this.$message.error(this.$t("validation.username"));
            } else {
              this.$message.error(this.$t("table.add_fail"));
            }
            
          });
        } else {
          return false;
        }
      });
    },
    close() {
      this.dialogTableVisible = false;
    },
  },
};
</script>
<style>
/* 图片上传的样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
}
/* 头像(product_main_photo)图片上传组件的尺寸 */
.upload_product_main_photo .avatar-uploader-icon {
  font-size: 28px;
  min-width: 178px;
  height: 178px;
  line-height: 178px;
}
.upload_product_main_photo .avatar {
  min-width: 178px;
  height: 178px;
}
</style>
